$.fn.serializeObject = function() {
    var o = {};
    var arr = this.serializeArray();
    $.each(arr,function(){
        if (o[this.name]) {  //返回json中有该属性
            if (!o[this.name].push) { //将已存在的属性值改成数组
                o[this.name] = [ o[this.name] ];
            }
            o[this.name].push(this.value || null); //将值存放到数组中
        } else {  //返回json中没有有该属性
            o[this.name] = this.value || null;  //直接将属性和值放入返回json中
        }
    });
    return o;
}

var url;
function addGoods(){
    $('#dlg').dialog('open').dialog('setTitle','新增商品');
    $('#fm').form('clear');
    url = '/goods/create';
}
function editGoods(){
    var row = $('#dg').datagrid('getSelected');
    if (row){
        $('#dlg').dialog('open').dialog('setTitle','编辑商品');
        $('#fm').form('load',row);
        url = '/goods/update?id='+row.id;
    }
}
function viewGoods(){
    var row = $('#dg').datagrid('getSelected');
    if (row){
        $('#info-dialog').dialog('open').dialog('setTitle','商品详情');
        for(var propName in row){
            if(row[propName]==null){
                row[propName]=''
            }
            $("#info-"+propName+"").text(row[propName]);
        }
    }
}

function saveGoods(){
    $('#fm').form('submit',{
        url: url,
        onSubmit: function(){
            return $(this).form('validate');
        },
        success: function(result){
            result=JSON.parse(result);
            if (result.success){
                $('#dlg').dialog('close');
                $('#dg').datagrid('reload');
            }
            else {
                $.messager.show({
                    title: '保存失败',
                    msg: result.message
                });
            }
        }
    });
}

function removeGoods(){
    var row = $('#dg').datagrid('getSelected');
    if (row){
        $.messager.confirm('确认','确定删除该商品吗?',function(yes){
            if (yes){
                $.ajax({
                    url:'/goods/delete',
                    method:"delete",
                    data:{id:row.id},
                    success:function(result){
                        if (result.success){
                            $('#dg').datagrid('reload');
                        } else {
                            $.messager.show({
                                title: 'Error',
                                msg: result.msg
                            });
                        }
                    }
                });
            }
        });
    }
}

function searchGoods(){
    var formData = $('#search-form').serializeObject();
    loadGoods(formData);
}

function reset(){
    $('#search-form').form('clear');
}

function exportExcel(){
    var formData = $('#search-form').serializeObject();
    window.open('/goods/export','_blank');
}

function loadGoods(queryParams) {
    $('#dg').datagrid({
        url:"/goods/queryByPage",
        method:"get",
        queryParams: queryParams
    });
}

$(function () {
   loadGoods({});
});